package cn.z2huo.knowledge.concurrency.threadlocal;

import cn.hutool.core.thread.ThreadUtil;
import lombok.Data;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *
 * @author z2huo
 */
class ThreadLocalTest {

    @Data
    static class Foo {

        /**
         * 实例总数
         */
        static final AtomicInteger AMOUNT = new AtomicInteger(0);

        /**
         * 对象的编号
         */
        int index = 0;

        /**
         * 对象的内容
         */
        int bar = 10;

        public Foo() {
            // 总数增加，并且给对象编号，编号从 0 开始
            index = AMOUNT.incrementAndGet();
        }

        @Override
        public String toString() {
            return index + "@Foo{bar=" + bar + '}';
        }
    }

//    private static final ThreadLocal<Foo> FOO_THREAD_LOCAL = new ThreadLocal<>();

    private static final ThreadLocal<Foo> FOO_THREAD_LOCAL = ThreadLocal.withInitial(Foo::new);

    public static void main(String[] args) {

        ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        // 5 个线程
        for (int i = 0; i < 5; i++) {
            threadPool.execute(() -> {
//                if (FOO_THREAD_LOCAL.get() == null) {
//                    FOO_THREAD_LOCAL.set(new Foo());
//                }
                System.out.println(Thread.currentThread().getName() + ", thread local value is " + FOO_THREAD_LOCAL.get());

                // 每个线程执行 10 次
                for (int j = 0; j < 10; j++) {
                    Foo foo = FOO_THREAD_LOCAL.get();
                    // 对象内容递增
                    foo.setBar(foo.getBar() + 1);
                    // sleep 50 毫秒
                    ThreadUtil.sleep(50);
                }
                System.out.println(Thread.currentThread().getName() + ", after incr, thread local value is " + FOO_THREAD_LOCAL.get());

                FOO_THREAD_LOCAL.remove();
            });
        }

        threadPool.close();
    }

}
